﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    linkTable=T_RES_LINK;
    table=T_RES_LOCATION;
    itemModel=new QStandardItemModel(this);
    ui->entryView->setModel(itemModel);
    ui->entryView->setEditTriggers(QTreeView::NoEditTriggers);

    startSynchronizer();
    updateView();
    createMenu();
    loadLocation();

    fetcher=new Fetcher(this);
    ui->tabWidget->addTab(fetcher,QStringLiteral("下载"));
}

Widget::~Widget()
{
    saveLocation();
    stopSynchronizer();
    delete ui;
}

void Widget::updateView()
{
    form=WF_NORMAL;
    itemModel->clear();
    itemModel->setHorizontalHeaderLabels(QStringList() << "Organization");
    QSqlQuery query;
    query.exec(QString("select category from %1").arg(table));
    while(query.next())
    {
        QString category=query.value("category").toString();
        QStandardItem *p_item=new QStandardItem(category);
        p_item->appendRows(getLabelItems(category));
        itemModel->appendRow(p_item);
    }
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("查找"),this,&Widget::showSearchBox);
    menu->addAction(QStringLiteral("打开视频目录"),
                    this,&Widget::openTopicLocation);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新视图"),
                    this,&Widget::updateView);
}

void Widget::showSearchBox()
{
    QString keyword=QInputDialog::getText(this,QStringLiteral("输入关键词"),QStringLiteral("关键词"));
    if(keyword.isEmpty())
        return;

    form=WF_SEARCH;
    itemModel->clear();
    itemModel->setHorizontalHeaderLabels(QStringList() << QStringLiteral("类别") << keyword);

    QSqlQuery query;
    QString sql=QString("select category,label from %1 where label like '%%2%'")
            .arg(table)
            .arg(keyword);
    query.exec(sql);
    while(query.next())
    {
        QString category=query.value("category").toString();
        QString label=query.value("label").toString();
        QList<QStandardItem *> items;
        items.append(new QStandardItem(category));
        items.append(new QStandardItem(label));
        itemModel->appendRow(items);
    }
}

void Widget::collapseAll()
{
    ui->entryView->collapseAll();
}

void Widget::updateTopicLocation()
{
    if(!topicLocations.isEmpty())
        topicLocations.clear();

    QSqlQuery query;
    query.exec(QString("select label,detail from %1 where category='Location'")
               .arg(table));
    while (query.next()) {
        QString label=query.value(0).toString();
        QString detail=query.value(1).toString();
        topicLocations.insert(label,detail);
    }
}

void Widget::openTopicLocation()
{
    if(topicLocations.isEmpty())
        return;

    QModelIndex index=ui->entryView->currentIndex();
    if(index.isValid())
    {
        QString category=getCategoryByIndex(index);
        if(category.isEmpty())
            return;

        QString detail=topicLocations.value(category);
        if(detail.isEmpty())
            return;
        if(QDir(detail).exists())
            QDesktopServices::openUrl(QUrl::fromLocalFile(detail));
    }
}

void Widget::startSynchronizer()
{
    synchronizer=new LocationSynchronizer;
    synchronizer->awake(linkTable,table);
    connect(&syncThread,&QThread::finished,synchronizer,&QObject::deleteLater);
    synchronizer->moveToThread(&syncThread);
    syncThread.start();
}

void Widget::stopSynchronizer()
{
    syncThread.quit();
    syncThread.wait();
}

void Widget::on_entryView_clicked(const QModelIndex &index)
{
    if(!index.isValid())
        return;

    if(!getItemByIndex(index))
        return;

    if(!getDetail())
        return;

    if(!detail.isEmpty())
    {
        QFileInfo fileInfo(detail);
        QString baseName=fileInfo.baseName();
        if(QFile::exists(baseName + ".png"))
            baseName += ".png";
        else if(QFile::exists(baseName + ".jpg"))
            baseName += ".jpg";

    }
}

void Widget::on_entryView_doubleClicked(const QModelIndex &index)
{
    if(!index.isValid())
        return;

    if(!detail.isEmpty())
    {
        if(QFile::exists(detail))
            QDesktopServices::openUrl(QUrl::fromLocalFile(detail));
    }
}
